import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@WebServlet("/get_prompt")

public class GetPrompt extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        String id = req.getParameter("id");
        if (id == null) {
            throw new ServletException("please input id");
        }

        PrintWriter out = resp.getWriter();

        String prompt = getRedisValue(id);

        if (prompt != null && prompt.length() != 0) {
            out.printf("%s", prompt);
        } else {
            prompt = getPrompt(getJDBCConnection(), id);
            delKey(id);
            setRedisValue(id, prompt);
            out.printf("%s", prompt);
        }
        out.close();
    }

    public String getPrompt(final Connection conn, String id) throws ServletException {
        Statement stmt = null;
        ResultSet rs = null;
        String prompt = "";
        try {
            stmt = conn.createStatement();
            String sql = String.format("SELECT * FROM t_ai_painting WHERE id = %s", id);
            rs = stmt.executeQuery(sql);

            if (rs.next()) {
                do {
                    prompt = rs.getString("prompt");
                } while (rs.next());
            } else {
                throw new ServletException("prompt info not exist");
            }
        } catch (Exception e) {
            throw new ServletException(e);
        } finally {
            try {
                rs.close();
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return prompt;
    }
}
